Retrieving a feed from a different domain
The news feed that we've
been using for our example is a local file, but we might want to
retrieve a feed from another site altogether. As we saw in Chapter 6,
AJAX requests cannot, as a rule, be made to a different site than the
one hosting the page being viewed. There, we discussed the JSONP data
format as a method for circumventing this limitation. Here, though,
we'll assume we cannot modify the data source, so we need a different
solution.
To allow AJAX to fetch this file, we'll use some server-side code as a proxy
for the request, so that JavaScript believes the XML file is on our
server even though it actually resides on a different one. We will
write a short PHP script to pull the content of the news feed to our
server, and relay that data to the requesting jQuery script. This
script, which we'll call feed.php, can be called in the same way feed.xml was fetched previously:
$.get('news/feed.php', function(data) {
// ...
});
Inside the feed.php file, we pull in the content of the news feed from the remote site, then print the content as the output of the script.
<?php
header('Content-Type: text/xml');
print file_get_contents('http://jquery.com/blog/feed');
?>
Note here that we need to explicitly set the content type of the page to text/xml so that jQuery can fetch it and parse it as if it were a normal, static XML document.
Some web-hosting providers may not allow the use of the PHP file_get_contents() function to fetch remote files because of security concerns. In these cases, alternative solutions, such as using the cURL library, may be available. More information on this library can be found at http://wiki.dreamhost.com/CURL.
Adding a loading indicator
Pulling in a remote file
like this might take some time, depending on a number of factors, so we
should inform the user that loading is in progress. To do this, we'll
add a loading indicator image to the page before we issue our AJAX request.
var $loadingIndicator = $('<img/>')
.attr({
'src': 'images/loading.gif',
'alt': 'Loading. Please wait.'
})
.addClass('news-wait')
.appendTo($container);
Then, as the first line of our $.get() function's success callback, we can remove the image from the page with a simple command:
$loadingIndicator.remove();
Now, when the page first
loads, if there is a delay in retrieving the headline content, we'll
see a loading image rather than an empty area.
This image is an animated GIF, and in a web browser will spin to signify that activity is taking place.
We can easily create new animated GIF images for use as AJAX loading indicators by using the service at http://ajaxload.info/.